package com.chaos.meta.util;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author naicha
 * @date 2020/7/21 17:53
 * @description: Encryption and Decryption Util
 */
@Slf4j
@Component
public final class CryptoUtil {
    private CryptoUtil() {
    }

    private static final String ALGORITHM = "AES";

    /**
     * 默认加密的KEY
     */
    private static String KEY_DEFAULT ;

    @Value("${aes.default.key}")
    private void setKeyDefault(String keyDefault)
    {
    	CryptoUtil.KEY_DEFAULT = keyDefault;
    }

    /**
     * 算法/工作模式/补码方式
     */
    private static String TRANSFORM_ECB_PKCS5;

    @Value("${aes.model}")
    private void setTransform_Ecb(String transform_Ecb)
    {
    	CryptoUtil.TRANSFORM_ECB_PKCS5 = transform_Ecb;
    }

    /**
     * 基于ECB工作模式的AES加密
     *
     * @param value 待加密字符串
     * @return java.lang.String
     */
    public static String encryptEcbMode(final String value) {
        if (StringUtils.isNotEmpty(value)) {
            //密码
            final SecretKeySpec keySpec = getSecretKey();
            try {
                Cipher encipher = Cipher.getInstance(TRANSFORM_ECB_PKCS5);

                //加密模式
                encipher.init(Cipher.ENCRYPT_MODE, keySpec);
                //使用AES加密
                byte[] encrypted = encipher.doFinal(getUTF8Bytes(value));
                //然后转成BASE64返回
                return Base64.encodeBase64String(encrypted);
            } catch (Exception e) {
                log.error("fail to encryptEcbMode, the detail is :" + e);
            }
        }

        return value;
    }

    /**
     * 基于ECB工作模式的AES解密
     *
     * @param encryptedStr AES加密之后的字符串
     * @return String
     */
    public static String decryptEcbMode(final String encryptedStr) {
        if (StringUtils.isNotEmpty(encryptedStr)) {
            //密码
            final SecretKeySpec keySpec = getSecretKey();
            try {
                Cipher encipher = Cipher.getInstance(TRANSFORM_ECB_PKCS5);

                //加密模式
                encipher.init(Cipher.DECRYPT_MODE, keySpec);
                //先用BASE64解密
                byte[] encryptedBytes = Base64.decodeBase64(encryptedStr);
                //然后再AES解密
                byte[] originalBytes = encipher.doFinal(encryptedBytes);
                //返回字符串
                return new String(originalBytes);
            } catch (Exception e) {
                log.error("fail to decryptEcbMode, the detail is :" + e);
            }
        }
        return encryptedStr;
    }

    /**
     * 将字符串转化为UTF8格式的byte数组
     *
     * @param input the input string
     * @return UTF8 bytes
     */
    private static byte[] getUTF8Bytes(String input) {
        return input.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 生成加密秘钥
     *
     * @return SecretKeySpec
     */
    private static SecretKeySpec getSecretKey()
    {
        //生成指定算法密钥
        KeyGenerator generator = null;
        try {
            generator = KeyGenerator.getInstance(ALGORITHM);

            //指定AES密钥长度（128、192、256）
            generator.init(256, new SecureRandom(getUTF8Bytes(KEY_DEFAULT)));

            //生成一个密钥
            SecretKey secretKey = generator.generateKey();
            //转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            log.error("fail to getSecretKey, the detail is :" + ex);
        }
        return null;
    }
}